package com.syezon.wifikey.view.verticalbannerview;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.syezon.wifikey.R;
import com.syezon.wifikey.analysis.AnalysisHelper;


@SuppressWarnings("unused")
public class VerticalBannerView extends LinearLayout implements BaseBannerAdapter.OnDataChangedListener {

    private float mBannerHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
    private int mGap = 4000;
    private int mAnimDuration = 1000;

    private BaseBannerAdapter mAdapter;

    private View mFirstView;
    private View mSecondView;

    private int mPosition;

    private boolean mIsStarted;
    private Paint mDebugPaint;
    private Animator mAnim;
    private AnimRunnable mRunnable = new AnimRunnable();

    private boolean mAutoStart;
    private boolean mIsStop;

    public VerticalBannerView(Context context) {
        this(context, null);
    }

    public VerticalBannerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public VerticalBannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    /**
     * bannerHeight banner的高度
     * animDuration 每次切换动画时间
     * gap banner切换时间
     */
    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        setOrientation(VERTICAL);
        mDebugPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.VerticalBannerView);
        mGap = array.getInteger(R.styleable.VerticalBannerView_gap, mGap);
        mAutoStart = array.getBoolean(R.styleable.VerticalBannerView_auto_start, true);
        mAnimDuration = array.getInteger(R.styleable.VerticalBannerView_animDuration, mAnimDuration);

        if (mGap <= mAnimDuration) {
            mGap = 4000;
            mAnimDuration = 1000;
        }

        array.recycle();
    }

    public BaseBannerAdapter getAdapter() {
        return mAdapter;
    }

    /**
     * 设置banner的数据
     */
    public void setAdapter(BaseBannerAdapter adapter) {
        if (adapter == null) {
            throw new RuntimeException("adapter must not be null");
        }
        this.mAdapter = adapter;
        mAdapter.setOnDataChangedListener(this);
        setupAdapter();
    }

    public void start() {
        if (!mIsStarted && mAdapter != null && mAdapter.getCount() > 1) {
            mIsStarted = true;
            removeCallbacks(mRunnable);
            postDelayed(mRunnable, mGap);
            mIsStop = false;
        }
    }

    public void stop() {
        removeCallbacks(mRunnable);
        if (mAnim != null && mAnim.isRunning()) {
            mAnim.cancel();
        }
        mIsStarted = false;
        mIsStop = true;
    }

    private void setupAdapter() {
        removeAllViews();
        if (mAdapter != null && mAdapter.getCount() > 0) {
            if (mAdapter.getCount() == 1) {
                mFirstView = mAdapter.getView(this);
                mAdapter.setItem(mFirstView, mAdapter.getItem(0));
                addView(mFirstView);
            } else {
                mFirstView = mAdapter.getView(this);
                mSecondView = mAdapter.getView(this);
                mAdapter.setItem(mFirstView, mAdapter.getItem(0));
                mAdapter.setItem(mSecondView, mAdapter.getItem(1));
                addView(mFirstView);
                addView(mSecondView);
                mPosition = 0;
                mIsStarted = false;
            }
            setBackgroundDrawable(mFirstView.getBackground());
            if (mAutoStart && !mIsStop) {
                start();
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mBannerHeight = getMeasuredHeight();
        if (isInEditMode()) {
            setBackgroundColor(Color.GRAY);
            return;
        }
        if (mFirstView != null) {
            ViewGroup.LayoutParams layoutParams = mFirstView.getLayoutParams();
            layoutParams.height = (int) mBannerHeight;
            mFirstView.setLayoutParams(layoutParams);
        }
        if (mSecondView != null) {
            ViewGroup.LayoutParams layoutParams = mSecondView.getLayoutParams();
            layoutParams.height = (int) mBannerHeight;
            mSecondView.setLayoutParams(layoutParams);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (isInEditMode()) {
            mDebugPaint.setColor(Color.WHITE);
            mDebugPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
            mDebugPaint.setStyle(Paint.Style.STROKE);
            canvas.drawText("banner is here", 20, getHeight() * 2 / 3, mDebugPaint);
        }
    }

    @Override
    public void onChanged() {
        setupAdapter();
    }

    private void performSwitch() {
        if (mAdapter != null && mAdapter.getCount() > 0
                && mFirstView != null && mSecondView != null) {
            if (mAnim != null && mAnim.isRunning()) {
                mAnim.cancel();
            }
            ObjectAnimator animator1 = ObjectAnimator.ofFloat(mFirstView, "translationY", mFirstView.getTranslationY() - mBannerHeight);
            ObjectAnimator animator2 = ObjectAnimator.ofFloat(mSecondView, "translationY", mSecondView.getTranslationY() - mBannerHeight);
            mAnim = new AnimatorSet();
            AnimatorSet animatorSet = (AnimatorSet) this.mAnim;
            animatorSet.playTogether(animator1, animator2);
            this.mAnim.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    if (mFirstView != null && mSecondView != null && mAdapter != null && mAdapter.getCount() > 0) {
                        mFirstView.setTranslationY(0);
                        mSecondView.setTranslationY(0);
                        View removedView = getChildAt(0);
                        mPosition++;
                        mAdapter.setItem(removedView, mAdapter.getItem(mPosition % mAdapter.getCount()));
                        removeView(removedView);
                        addView(removedView, 1);
                    }
                }

            });
            mAnim.setDuration(mAnimDuration);
            mAnim.start();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stop();
    }

    @Override
    protected void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private class AnimRunnable implements Runnable {

        @Override
        public void run() {
            try {
                performSwitch();
                postDelayed(this, mGap);
            } catch (Exception e) {
                AnalysisHelper.reportError(e);
            }
        }
    }
}
















